package com.ruoyi.yipaiju.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.BizConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.yipaiju.domain.ServerManage;
import com.ruoyi.yipaiju.service.IServerManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 服务器Controller
 * 
 * @author liuwp
 * @date 2023-06-19
 */
@RestController
@RequestMapping("/yipaiju/server_manage")
public class ServerManageController extends BaseController
{
    @Autowired
    private IServerManageService serverManageService;

    /**
     * 查询服务器列表
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:list')")
    @GetMapping("/list")
    public TableDataInfo list(ServerManage serverManage)
    {
        startPage();
        List<ServerManage> list = serverManageService.selectServerManageList(serverManage);
        list.forEach(item -> {
            // 中间替换为*
            item.setPassword(StringUtils.strReplaceMil(item.getPassword(), 8));
            if (StringUtils.isNotEmpty(item.getGrabType())){
                item.setGrabTypes(item.getGrabType().split(","));
            }
            if (StringUtils.isNotEmpty(item.getGrabMold())){
                item.setGrabMolds(item.getGrabMold().split(","));
            }
        });
        return getDataTable(list);
    }

    /**
     * 导出服务器列表
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:export')")
    @Log(title = "服务器", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ServerManage serverManage)
    {
        List<ServerManage> list = serverManageService.selectServerManageList(serverManage);
        ExcelUtil<ServerManage> util = new ExcelUtil<ServerManage>(ServerManage.class);
        util.exportExcel(response, list, "服务器数据");
    }

    /**
     * 获取服务器详细信息
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        ServerManage serverManage = serverManageService.selectServerManageById(id);
        if (StringUtils.isNotEmpty(serverManage.getGrabType())){
            serverManage.setGrabTypes(serverManage.getGrabType().split(","));
        }
        if (StringUtils.isNotEmpty(serverManage.getGrabMold())){
            serverManage.setGrabMolds(serverManage.getGrabMold().split(","));
        }
        return AjaxResult.success(serverManage);
    }

    /**
     * 新增服务器
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:add')")
    @Log(title = "服务器", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ServerManage serverManage)
    {
        if (serverManage.getGrabTypes() != null){
            serverManage.setGrabType(StringUtils.join(serverManage.getGrabTypes(), ","));
        }
        if (serverManage.getGrabMolds() != null){
            serverManage.setGrabMold(StringUtils.join(serverManage.getGrabMolds(), ","));
        }
        return toAjax(serverManageService.insertServerManage(serverManage));
    }

    /**
     * 修改服务器
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:edit')")
    @Log(title = "服务器", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ServerManage serverManage)
    {
        if (serverManage.getGrabTypes() != null){
            serverManage.setGrabType(StringUtils.join(serverManage.getGrabTypes(), ","));
        }
        if (serverManage.getGrabMolds() != null){
            serverManage.setGrabMold(StringUtils.join(serverManage.getGrabMolds(), ","));
        }
        return toAjax(serverManageService.updateServerManage(serverManage));
    }

    /**
     * 删除服务器
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:remove')")
    @Log(title = "服务器", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(serverManageService.deleteServerManageByIds(ids));
    }

    /***************************************/

    /**
     * 爬虫添加省份
     * @param id
     * @return
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:addprov')")
    @GetMapping(value = "serverAddprov/{id}")
    public AjaxResult serverAddprov(@PathVariable("id") Long id)
    {
        return AjaxResult.success(serverManageService.serverAddProv(serverManageService.selectServerManageById(id)));
    }

    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:adddetail')")
    @GetMapping(value = "serverAdddetail/{id}")
    public AjaxResult serverAdddetail(@PathVariable("id") Long id)
    {
        serverManageService.serverAdddetailDispatchItem(serverManageService.selectServerManageById(id));
        return AjaxResult.success();
    }

    /**
     * 请空队列
     * @param id
     * @param queuePrefix
     * @return
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:clearqueue')")
    @GetMapping(value = "clearQueue/{id}")
    public AjaxResult clearQueue(@PathVariable("id") Long id, String queuePrefix)
    {
        ServerManage serverManage = serverManageService.selectServerManageById(id);
        String queueName = queuePrefix + StringUtils.dreX(serverManage.getServerIp());
        if (serverManageService.serverClearQueue(queueName)){
            if (BizConstants.Spider.ALILQNAME.equals(queuePrefix)){
                serverManage.setQueueProvCount(0);
            }
            if (BizConstants.Spider.ALIDQNAME.equals(queuePrefix)){
                serverManage.setQueueDetailCount(0);
            }
            if (BizConstants.Spider.JDDQNAME.equals(queuePrefix)){
                serverManage.setQueueDetailCountJd(0);
            }
            if (BizConstants.Spider.GPWDQNAME.equals(queuePrefix)){
                serverManage.setQueueDetailCountGpw(0);
            }
            if (BizConstants.Spider.ZPPTDQNAME.equals(queuePrefix)){
                serverManage.setQueueDetailCountZppt(0);
            }
            if (BizConstants.Spider.SSZCWDQNAME.equals(queuePrefix)){
                serverManage.setQueueDetailCountSszcw(0);
            }
            if (BizConstants.Spider.ICBCDQNAME.equals(queuePrefix)){
                serverManage.setQueueDetailCountIcbc(0);
            }
            if (BizConstants.Spider.CBEXDQNAME.equals(queuePrefix)){
                serverManage.setQueueDetailCountCbex(0);
            }
            serverManageService.updateServerManage(serverManage);
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 远程更新
     * @param id
     * @return
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:arrange')")
    @GetMapping(value = "spiderArrange/{id}")
    public AjaxResult spiderArrange(@PathVariable("id") Long id)
    {
        ServerManage serverManage = serverManageService.selectServerManageById(id);
        if (serverManageService.serverSpiderArrange(serverManage)){
            // TODO 可以更新下爬虫版本
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 批量更新
     * @param ids
     * @return
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:arrange')")
    @DeleteMapping(value = "spiderArranges/{ids}")
    public AjaxResult spiderArranges(@PathVariable Long[] ids)
    {
        try {
            ExecutorService executorService = Executors.newFixedThreadPool(ids.length);
            for (Long id : ids) {
                executorService.execute(() -> {
                    try {
                        ServerManage serverManage = serverManageService.selectServerManageById(id);
                        serverManageService.serverSpiderArrange(serverManage);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                });
            }
            executorService.shutdown();
            while (true) {
                Thread.sleep(100);
                if(executorService.isTerminated()){
                    break;
                }
            }
            return AjaxResult.success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.error();
    }

    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:start')")
    @GetMapping(value = "spiderStart/{id}")
    public AjaxResult spiderStart(@PathVariable("id") Long id)
    {
        ServerManage serverManage = serverManageService.selectServerManageById(id);
        if (serverManageService.spiderStart(serverManage)){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }


    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:shutdown')")
    @GetMapping(value = "spiderShutdown/{id}")
    public AjaxResult spiderShutdown(@PathVariable("id") Long id)
    {
        ServerManage serverManage = serverManageService.selectServerManageById(id);
        if (serverManageService.spiderShutdown(serverManage)){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:shutdown')")
    @DeleteMapping(value = "spiderShutdowns/{ids}")
    public AjaxResult spiderShutdowns(@PathVariable Long[] ids)
    {
        try {
            ExecutorService executorService = Executors.newFixedThreadPool(ids.length);
            for (Long id : ids) {
                executorService.execute(() -> {
                    try {
                        ServerManage serverManage = serverManageService.selectServerManageById(id);
                        serverManageService.spiderShutdown(serverManage);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                });
            }
            executorService.shutdown();
            while (true) {
                Thread.sleep(100);
                if(executorService.isTerminated()){
                    break;
                }
            }
            return AjaxResult.success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.error();
    }


    /**
     * 同步队列
     * @param id
     * @return
     */
    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:synchqueue')")
    @GetMapping(value = "synchQueue/{id}")
    public AjaxResult synchQueue(@PathVariable("id") Long id)
    {
        ServerManage serverManage = serverManageService.selectServerManageById(id);
        serverManageService.serverSynchQueue(serverManage);
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('yipaiju:server_manage:synchqueue')")
    @GetMapping(value = "synchQueue/all")
    public AjaxResult synchQueueAll()
    {
        serverManageService.serverSynchQueueCount();
        return AjaxResult.success();
    }


    public static void main(String[] args) throws Exception{
        String sdkPath = "C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python311\\python.exe";
        String codePath = "C://Spider/AliSpider";
        String command = sdkPath + " "+codePath+"/QueueLen.py QueueProv";

//        tasklist | findstr python   查看进行列表
//        command = "taskkill /F /IM python.exe";
//
//
////        command = "C:\\Spider\\RunAliList.bat";
//
//        String result = CurrencyUtil.remoteExecCmd("175.178.49.72", "Administrator", "5uC4MHH6@6d8%Y4H", command);
//
//        System.out.println("===="+result.trim()+"---");


        System.out.println(URLDecoder.decode("%C9%BD%CE%F7", "utf-8"));
    }
}
